package com.net.requesthandler
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;

	public class upLoadFile
	{
		private var fileName:String;//文件名
		
		private var Content_Type:String;//文件类型
		
		private var bytes:ByteArray;//数据
		
		private var stream:FileStream;//写入
		
		private var readLength:int;//本段数据长度  由于为了节省资源  传入的byte组为原始数组 
		
		public function upLoadFile(b:ByteArray,rl:int)
		{
			bytes=b;
			readLength=rl;
			//bytes.position=0;
			
			findFileName();
		}
		
		private function findFileName():void{
			readLineExpress();
			var firstLine:String=readLineExpress();
			var nameIndex:int=firstLine.indexOf("filename=");
			if(nameIndex!=-1){
				fileName=firstLine.substring(nameIndex+10,firstLine.length-1);
				if(fileName==""){
					//fileName=new Date().toString();
					fileName="default";
				}
			}else{
				//数据段不是上传的文件数据段
				return;
			}
			
			var line:String=readLineExpress();
			while(line!=""){
				//附加的其他参数
				
				
				line=readLineExpress();
			}
			
			var file:File=new File(File.applicationDirectory.resolvePath(fileName).nativePath);
			stream=new FileStream();
			stream.open(file,FileMode.WRITE);
			
			//将数据取出
			var fileTe:ByteArray=new ByteArray();
			bytes.readBytes(fileTe,0,readLength);
			
			stream.writeBytes(fileTe,0,fileTe.length-3);
			stream.close();
		}
		
		/**
		 * 检查自 startAt 起第一个双回车
		 * 
		 * 如果全局没有找到则返回-1
		 */
		private function findDoubleBreak(startAt:int=0):int{
			var out:int=-1;
			for (var i:int=startAt;i<bytes.length;i++ ){
				if ((bytes[i] == 13 ) && 
					(bytes[i+1] == 10) &&
					(bytes[i+2] == 13 ) &&
					(bytes[i+3] == 10)) {
					out = i;
					break;
				}
			}
			return out;
		}
		
		/**
		 * 快速读取一行
		 */
		private function readLineExpress():String{
			var line:ByteArray=new ByteArray();
			readLength--;
			var oneByte:int;
			while(true){
				oneByte=bytes.readByte();
				readLength--;
				if(oneByte==13){
					oneByte=bytes.readByte();
					if(oneByte==10){
						return line.toString();
					}
					line.writeByte(13);
				}
				line.writeByte(oneByte);
			}
			return line.toString();
		}
	}
}